<script lang="ts">
  import { derived } from "svelte/store";
  import { actixGraphqlEndpoint } from "$lib/js/stores";

  import Tabs from "$lib/Tabs.svelte";
  import type { File, Folder, TabType, KV, Editor } from "$lib/ebm";
  import FolderNav from "$lib/explorer/FolderNav.svelte";
  import { HSplitPane, VSplitPane } from "$lib/splitpane";
  import FolderDetail from "$lib/explorer/FolderDetail.svelte";
  import QuizDetail from "$lib/explorer/QuizDetail.svelte";
  import UnsupportedEditor from "$lib/explorer/UnsupportedEditor.svelte";
  import QuizItemDetail from "$lib/explorer/QuizItemDetail.svelte";

  import { request, gql } from "graphql-request";

  import {
    useQuery,
    useMutation,
    useQueryClient,
  } from "@sveltestack/svelte-query";

  let classPointerEventsNone;
  const onMouseDown = () => {
    classPointerEventsNone = "pointer-events-none";
  };
  const onMouseUp = () => {
    classPointerEventsNone = "";
  };

  let endpoint = $actixGraphqlEndpoint;
  const FOLDER_QUERY = gql`
    query {
      folder: findTopFolder {
        id
        folderName
        snapshotAt
        seq
        title
        description
        refererUrl
        ancestry
        createdAt
        updatedAt
        status
        pid
        from
        folders {
          id
          folderName
          snapshotAt
          seq
          title
          description
          refererUrl
          ancestry
          createdAt
          updatedAt
          status
          pid
          from
          folders {
            id
            folderName
            snapshotAt
            seq
            title
            description
            refererUrl
            ancestry
            createdAt
            updatedAt
            status
            pid
            from
            folders {
              id
              folderName
              snapshotAt
              seq
              title
              description
              refererUrl
              ancestry
              createdAt
              updatedAt
              status
              pid
              from
              folders {
                id
                folderName
                snapshotAt
                seq
                title
                description
                refererUrl
                ancestry
                createdAt
                updatedAt
                status
                pid
                from
              }
            }
          }
        }
      }
    }
  `;

  const queryFolderResult = useQuery<Folder, { message: string }>(
    "folder",
    async () => {
      const { folder } = await request(endpoint, FOLDER_QUERY);
      return folder;
    }
  );

  const EDITORS_QUERY = gql`
    query {
      editors: listEditors(page: 0) {
        id
        snapshotAt
        title
        createdAt
        updatedAt
        status
        from
      }
    }
  `;

  const queryEditorsResult = useQuery<Editor[], { message: string }>(
    "editors_query",
    async () => {
      const { editors } = await request(endpoint, EDITORS_QUERY);
      return editors;
    }
  );

  $: tab_items = derived(
    queryEditorsResult,
    ({ data, ...$queryEditorsResult }) => {
      let tab_items: TabType[] = [];

      if (data) {
        tab_items = data.map((x, i) => {
          let comp = UnsupportedEditor;
          let prefix = "";
          if (x.id.indexOf("fldr:") == 0) {
            comp = FolderDetail;
            prefix = "FD:";
          } else if (x.id.indexOf("quiz:") == 0) {
            comp = QuizDetail;
            prefix = "QZ:";
          } else if (x.id.indexOf("qitm:") == 0) {
            comp = QuizItemDetail;
            prefix = "QI:";
          }
          return {
            label: prefix + x.title,
            value: i + 1,
            title: x.title,
            component: comp,
            attributes: [{ k: "tab_id", v: x.id }],
          };
        });
      }

      return tab_items;
    }
  );

  const queryClient = useQueryClient();

  const closeEditorMutation = useMutation<
    Editor,
    { message: string },
    {
      id_: string;
    }
  >(
    async ({ id_ }) => {
      const { folder } = await request(
        endpoint,
        gql`
          mutation ($id: ID!) {
            folder: closeEditor(input: { id: $id }) {
              id
              snapshotAt
              title
              createdAt
              updatedAt
              status
              from
            }
          }
        `,
        {
          id: id_,
        }
      );
      return folder;
    },
    {
      onSuccess: () => {
        queryClient.invalidateQueries("editors_query");
      },
    }
  );

  function closeEditor(attributes: KV[]) {
    console.log("close from parent function attributes=", attributes);
    let tabid = attributes.find((x) => x.k == "tab_id");
    $closeEditorMutation.mutate({
      id_: tabid.v,
    });
  }
</script>

<div class="h-full w-full">
  <HSplitPane
    leftPaneSize="15%"
    rightPaneSize="85%"
    minLeftPaneSize="1px"
    minRightPaneSize="1px"
  >
    <left slot="left" class="overflow-hidden">
      {#if $queryFolderResult.isLoading}
        Loading...
      {:else if $queryFolderResult.isError}
        Error {$queryFolderResult.error.message}
      {:else}
        <FolderNav folder={$queryFolderResult.data} expanded />
      {/if}
    </left>
    <right slot="right">
      {#if tab_items}
        <Tabs
          items={$tab_items}
          closable={true}
          functionClose={(value) => closeEditor(value)}
        />
      {/if}
    </right>
  </HSplitPane>
</div>
